<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑新闻</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }

        .container {
            width: 80%;
            margin: 20px auto;
            overflow: hidden;
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        header {
            background: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
        }

        nav {
            display: flex;
            justify-content: center;
            background: #555;
            padding: 10px 0;
        }

        nav a {
            color: white;
            text-decoration: none;
            padding: 0 15px;
        }

        nav a:hover {
            background: #444;
        }

        form {
            margin-top: 20px;
        }

        form label {
            display: block;
            margin-bottom: 5px;
        }

        form input[type="text"],
        form textarea,
        form select {
            width: calc(100% - 20px);
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
        }

        form input[type="button"] {
            padding: 10px 20px;
            background: #333;
            color: #fff;
            border: none;
            cursor: pointer;
            float: right;
        }

        form input[type="button"]:hover {
            background: #444;
        }

        footer {
            background: #333;
            color: #fff;
            text-align: center;
            padding: 10px 0;
            position: relative;
            bottom: 0;
            width: 100%;
        }
    </style>
</head>

<body>
    <header>
        <h1>编辑新闻</h1>
    </header>
    <nav>
        <a href="index.html">返回首页</a>
    </nav>
    <div class="container">
        <h2>编辑新闻内容</h2>
        <form action="#" method="post" enctype="multipart/form-data">
            <label for="title">新闻标题：</label>
            <input type="text" id="title" name="title" value="新闻标题" required>
            <img class="newsImg" alt="新闻图片" width="200" id="news-image">
            <label for="image">上传图片：</label>
            <input type="file" class="file" id="image" name="image">

            <label for="content">新闻内容：</label>
            <textarea id="content" name="content" rows="10" required>
这里是新闻的详细内容，通常会包含新闻的全文，包括引言、正文和结论。
新闻内容可以包含多个段落，每个段落都详细描述了新闻事件的不同方面。
</textarea>

            <input type="button" class="update" value="更新新闻">
        </form>
    </div>
    <footer>
        <p>版权所有 © 2024 新闻网站</p>
    </footer>
</body>
<script src="./js/jquery-3.7.1.min.js"></script>
<script>
    $(".newsImg").hide();
     // 获得浏览器地址栏的参数
     let nid = window.location.search.substr(window.location.search.indexOf("nid")).split("=")[1];
    getNewsById()
    function getNewsById() {
        $.ajax({
            url: "http://www.dlrb.com:8082/news_detail.php",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            data: {
                nid
            },
            dataType: "json",
            success: (resp) => {
                if (resp.code == 200) {
                    $("#title").val(resp.data.title);
                    $("#content").val(resp.data.context);
                    if (resp.data.newImg) {
                        $(".newsImg").attr("src", resp.data.newImg);
                        $(".newsImg").show();
                    }
                    console.log(resp.data);
                } else {
                    alert(resp.msg)
                }
            },
            error: (resp) => {
                alert(resp.msg)
            }
        })
    }
    let newImg = ""
    $(".file").change(function () {
        // 手动构建表单
        let formData = new FormData()
        // 添加上传文件的二进制
        let file = $(".file")[0].files[0]
        formData.append("file", file)
        $.ajax({
            url: "http://www.dlrb.com:8082/upload.php",
            type: "POST",
            xhrFields: {
                withCredentials: true
            },
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: (resp) => {
                console.log(resp);
                if (resp.code == 200) {
                    alert(resp.msg)
                    newImg = resp.url
                } else {
                    alert(resp.msg)
                }
            },
            error: (resp) => {
                alert(resp.msg)
            }
        })
    })
    $(".update").click(() => {
        let cookie = cookieToJson(document.cookie)
        let username = cookie.username
        let role = cookie.role

        $.ajax({
            url: "http://www.dlrb.com:8082/updateNews.php",
            type: "GET",
            xhrFields: {
                withCredentials: true
            },
            data: {
                username,
                role,
                newImg,
                title: $("#title").val(),
                context: $("#content").val(),
                nid
            },
            dataType: "json",
            success: (resp) => {
                if (resp.code == 200) {
                    alert(resp.msg)
                    location.href = "index.html"
                } else {
                    alert(resp.msg)
                }
            },
            error: (resp) => {
                alert(resp.msg)
            }
        })
    })
    function cookieToJson(cookieString) {
        // 处理空字符串
        if (!cookieString || typeof cookieString !== 'string') {
            return {};
        }
        // 分割 Cookie 字符串
        const cookies = cookieString.split(';');
        const result = {};
        // 遍历每个 Cookie
        for (const cookie of cookies) {
            // 跳过空字符串
            if (!cookie.trim()) {
                continue;
            }
            // 查找第一个等号位置
            const equalsIndex = cookie.indexOf('=');

            // 如果没有等号，跳过这个 Cookie
            if (equalsIndex === -1) {
                continue;
            }
            // 提取键和值
            const name = cookie.substring(0, equalsIndex).trim();
            let value = cookie.substring(equalsIndex + 1).trim();
            // 处理可能的 URL 编码
            try {
                value = decodeURIComponent(value);
            } catch (e) {
                // 如果解码失败，使用原始值
                console.warn(`Failed to decode cookie value: ${value}`, e);
            }
            // 添加到结果对象
            result[name] = value;
        }
        return result;
    }
</script>

</html>